import React from 'react';
import ReactDOM from 'react-dom'
import 'styles/components/simple-flow/flow-grid.scss'

/**
 * 流程图用的栅栏布局，因为需要兼容IE9所以没有使用flex
 * 因为一行个数未知所以不能使用antd自带的Row、Col，因为他是24为最小公倍数
 * 这个组件给定一个基数，然后里面的按照基数分栏
 * 例如给定count = 5，则一行分5栏，内部用span比例进行栏内排列
 * 且每一行所有分栏高度一致，取最高的一栏
 */

/**
 * 这个类只是个代理，内部渲染用不到，随便给个span
 */
class FlowCol extends React.Component {

  render() {
    return <span/>;
  }

}

FlowCol.PropTypes = {
  span: React.PropTypes.number,
  _col: React.PropTypes.bool
};

FlowCol.defaultProps = {
  _col: true
};

/**
 * 内部根据children内的FlowCol进行分栏
 */
class FlowGrid extends React.Component {
  componentDidMount() {
    const { autoWidth } = this.props;
    //如果是自动计算宽度，则自动取父组件的宽度
    if (autoWidth) {
      this.dom = ReactDOM.findDOMNode(this.ref);
      // width: 100%，所以取的是父组件
      let width = this.dom.getBoundingClientRect().width;
      ReactDOM.render(<div>{this.renderChildren(width)}</div>, this.dom)
    }
  }

  renderChildren = width => {
    const { children, count } = this.props;
    let targetDom = [];
    let rowDom = [];
    let rowCount = 0;
    let colWidth = Math.floor(width / count);
    React.Children.map(children, child => {
      if(child) {
        const { _col, span, className = '', onClick = () => {} } = child.props;
        if (_col) {
          rowCount += span;
          rowDom.push(
            <div
              className={`flow-col ${className}`}
              key={rowDom.length}
              onClick={onClick}
              style={{ width: colWidth * span }}
            >
              {child.props.children}
            </div>
          );
          if (rowCount.toFixed(2) === count.toFixed(2)) {
            targetDom.push(
              <div
                key={targetDom.length}
                className="flow-row"
              >
                {[].concat(rowDom)}
              </div>
            );
            rowCount = 0;
            rowDom = [];
          }
        }
      }
    });
    return targetDom;
  };

  render() {
    const { width, autoWidth, className = '' } = this.props;
    return (
      <div className={`flow-grid ${className}`} style={autoWidth ? {} : { width }} ref={ref => this.ref = ref}>
        {!autoWidth && this.renderChildren(width)}
      </div>
    );
  }
}


FlowGrid.PropTypes = {
  count: React.PropTypes.number,
  width: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]),
  className: React.PropTypes.string,
  autoWidth: React.PropTypes.bool
};

FlowGrid.defaultProps = {};

FlowGrid.FlowCol = FlowCol;

export default FlowGrid;
